<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "shop_order".
 *
 * @property integer $order_id
 * @property integer $company_id
 * @property string $user_id
 * @property string $order_number
 * @property string $huiwenbi
 * @property integer $reciver_id
 * @property string $freight
 * @property string $express
 * @property string $express_no
 * @property integer $ship_time
 * @property integer $complete_time
 * @property integer $status
 * @property integer $order_type
 * @property string $activity_id
 * @property string $order_remarks
 * @property string $business_remarks
 * @property integer $is_del
 * @property integer $create_time
 */
class ShopOrder extends \yii\db\ActiveRecord
{
    public static function getDb()
    {
        return yii::$app->vrshop;
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'shop_order';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['company_id', 'user_id', 'reciver_id', 'ship_time', 'complete_time', 'status', 'order_type', 'activity_id', 'is_del', 'create_time'], 'integer'],
            [['huiwenbi', 'freight'], 'number'],
            [['order_remarks', 'business_remarks'], 'string'],
            [['order_number', 'express', 'express_no'], 'string', 'max' => 100],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'order_id' => 'Order ID',
            'company_id' => 'Company ID',
            'user_id' => 'User ID',
            'order_number' => 'Order Number',
            'huiwenbi' => 'Huiwenbi',
            'reciver_id' => 'Reciver ID',
            'freight' => 'Freight',
            'express' => 'Express',
            'express_no' => 'Express No',
            'ship_time' => 'Ship Time',
            'complete_time' => 'Complete Time',
            'status' => 'Status',
            'order_type' => 'Order Type',
            'activity_id' => 'Activity ID',
            'order_remarks' => 'Order Remarks',
            'business_remarks' => 'Business Remarks',
            'is_del' => 'Is Del',
            'create_time' => 'Create Time',
        ];
    }

    /**
     * 前台  获取订单类表   or  单订单详情
     * @param $order_id
     * @param string $goods_name
     * @param string $company_name
     * @param int $user_id
     * @param bool $order_status
     * @param int $page
     * @param int $size
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function GetOrder($order_id, $goods_name = '', $company_name = '', $user_id = 0, $order_status = false, $page = 1, $size = 10){
        $offset = ($page - 1) * $size;
        $and_where = '1 = 1 AND o.is_del = 0';
        if($order_id){
            $and_where .= " AND o.order_id = {$order_id}";
        }
        if($goods_name){
            $and_where .= " AND g.goods_name LIKE '%{$goods_name}%'";
        }
        if($company_name){
            $and_where .= " AND c.name LIKE '%{$company_name}%'";
        }
        if($order_status){
            $and_where .= " AND o.status = {$order_status}";
        }

        $order_list = self::find()
            ->alias('o')
            ->select([
                'o.order_id',
                'o.user_id',
                'o.order_number',
                'o.company_id',
                'c.name as company_name',
                'o.huiwenbi as total_price',
                'o.order_type',
                'o.freight',
                'o.express',
                'o.express_no',
                'o.ship_time',
                'o.complete_time',
                'o.status',
                'FROM_UNIXTIME(o.create_time) as create_time',
                'r.goods_num',
                'g.goods_id',
                'g.goods_name',
                'g.goods_type',
                'g.huiwenbi as price',
                'g.banner_image',
                'gav.price as attr_price',
                'gav.values_content',
            ])
            ->leftJoin('vrnews1.company c', 'o.company_id = c.company_id')
            ->leftJoin('vrshop.order_goods_relation r', 'o.order_id = r.order_id')
            ->leftJoin('vrshop.goods g', 'r.goods_id = g.goods_id')
            ->leftJoin('vrshop.goods_attribute_values gav', 'r.attribute_value_id = gav.values_id')
            ->where(['o.user_id'=>$user_id])
            ->andWhere($and_where)
            ->orderBy('o.create_time DESC')
            ->offset($offset)
            ->limit($size)
            ->asArray()
            ->all();

        $order_count = self::find()
            ->alias('o')
            ->leftJoin('vrnews1.company c', 'o.company_id = c.company_id')
            ->leftJoin('vrshop.order_goods_relation r', 'o.order_id = r.order_id')
            ->leftJoin('vrshop.goods g', 'r.goods_id = g.goods_id')
            ->where(['o.user_id'=>$user_id])
            ->andWhere($and_where)
            ->orderBy('o.create_time DESC')
            ->asArray()
            ->count();

        $order_list || $order_list = [];
        $order_count || $order_count = 0;

        if($order_id){
            return $order_list;
        }else{
            return ['count'=>$order_count, 'list'=>$order_list];
        }
        return [];
    }

    /**
     * 后台订单列表
     * @param $company_id
     * @param int $order_status
     * @param $order_sn
     * @param $consignee
     * @param $start_time
     * @param $end_time
     * @param $phone
     * @param int $page
     * @param int $size
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function BackendOrder($company_id, $order_type = false, $order_status = 0, $order_sn, $consignee, $start_time, $end_time, $phone, $page = 1, $size = 10){
        $offset = ($page - 1) * $size;
        $and_where = "1 = 1 AND o.is_del = 0";
        if($company_id){
            $and_where .= " AND o.company_id = {$company_id}";
        }
        if($order_type !== false){
            $and_where .= " AND g.goods_type = {$order_type}";
        }
        if($order_status){
            $and_where .= " AND o.status = {$order_status}";
        }
        if($order_sn){
            $and_where .= " AND o.order_number = '{$order_sn}'";
        }
        if($consignee){
            $and_where .= " AND a.consignee like '%{$consignee}%'";
        }
        if($start_time){
            $start_time = strtotime($start_time);
            $and_where .= " AND o.create_time > '{$start_time}'";
        }
        if($end_time){
            $end_time = strtotime($end_time);
            $and_where .= " AND o.create_time < '{$end_time}'";
        }
        if($phone){
            $and_where .= " AND a.phone = {$phone}";
        }

        $order_count = self::find()
            ->alias('o')
            ->leftJoin('vrshop.order_goods_relation r', 'o.order_id = r.order_id')
            ->leftJoin('vrshop.goods g', 'r.goods_id = g.goods_id')
            ->leftJoin('vrshop.user_address a', 'o.reciver_id = a.address_id')
            ->where($and_where)
            ->orderBy('o.create_time DESC')
            ->asArray()
            ->count();

        $order_list = self::find()
            ->alias('o')
            ->select([
                'o.order_id',
                'o.order_number',
                'o.huiwenbi as total_price',
                'r.goods_num',
                'g.goods_name',
                'g.huiwenbi as price',
                'g.banner_image',
                'g.goods_type',
                'o.freight',
                'o.order_type',
                'a.consignee',
                'a.phone',
                'CONCAT(a.prov,a.city,a.county,a.address) as full_address',
                "IF(o.status >= 1, '已支付', '未支付') as pay_status",
                'o.status as order_status',
                'FROM_UNIXTIME(o.create_time) as create_time',
            ])
            ->leftJoin('vrshop.order_goods_relation r', 'o.order_id = r.order_id')
            ->leftJoin('vrshop.goods g', 'r.goods_id = g.goods_id')
            ->leftJoin('vrshop.user_address a', 'o.reciver_id = a.address_id')
            ->where($and_where)
            ->orderBy('o.create_time DESC')
            ->offset($offset)
            ->limit($size)
            ->asArray()
            ->all();
//->createCommand()->getRawSql();

        $return_data = [];
        $order_list || $order_list = [];
        $order_count || $order_count = 0;

        $return_data = ['count'=>$order_count, 'list'=>$order_list];
        return $return_data;
    }

    /**
     * 后台  订单详情
     */
    public static function BackendOrderInfo($order_id){
        $order_info = self::find()
            ->alias('o')
            ->select([
                'o.order_id',
                'o.order_number',
                'o.huiwenbi as total_price',
                'o.freight',
                'o.ship_time',
                'o.complete_time',
                'r.goods_num',
                'g.goods_id',
                'g.goods_name',
                'g.goods_type',
                'g.huiwenbi as price',
                'g.banner_image',
                'a.consignee',
                'a.phone',
                'a.zipcode',
                'CONCAT(a.prov,a.city,a.county,a.address) as full_address',
                'o.status',
                'o.order_type',
                'o.order_remarks',
                'o.business_remarks',
                'o.express',
                'o.express_no',
                'o.status as order_status',
                'FROM_UNIXTIME(o.create_time) as create_time',
            ])
            ->leftJoin('vrshop.order_goods_relation r', 'o.order_id = r.order_id')
            ->leftJoin('vrshop.goods g', 'r.goods_id = g.goods_id')
            ->leftJoin('vrshop.user_address a', 'o.reciver_id = a.address_id')
            ->orderBy('o.create_time DESC')
            ->where(['o.order_id'=>$order_id])
            ->asArray()
            ->all();

        foreach ($order_info as &$order){
            if($order['goods_type'] == 2){
                $order['virtual_ship_info'] = VirtualOrderShip::find()
                    ->alias('vos')
                    ->select(['vos.ship_id', 'vgi.serial_number', 'vgi.password', 'vgi.deadline'])
                    ->leftJoin('vrshop.virtual_goods_info vgi', 'vos.details_id = vgi.details_id')
                    ->where(['vos.order_id'=>$order['order_id']])
                    ->asArray()
                    ->all();
            }else{
                $order['virtual_ship_info'] = '';
            }
        }
        unset($order);

        return $order_info;
    }

    /**
     * 根据订单获取商品信息
     * @param $order_id
     */
    public static function GetOrderGoods($order_id, $field = "g.*, o.*"){
        $info = self::find()
            ->alias('o')
            ->select($field)
            ->leftJoin('vrshop.order_goods_relation r', 'o.order_id = r.order_id')
            ->leftJoin('vrshop.goods g', 'r.goods_id = g.goods_id')
            ->where(['o.order_id'=>$order_id])
            ->asArray()
            ->one();

        $info || $info = [];
        return $info;
    }

    public static function getFreight($company_id, $goods_info, $address_info){
        //公司所在地区
        $company_info = Company::findOne($company_id)->toArray();
        if($goods_info['freight_type'] == 0){
            $freight = $goods_info['freight'];
        }else if($goods_info['freight_type'] == 1){
            //外省费用
            if($address_info['prov'] == $company_info['prov'] || $address_info['city'] == $company_info['prov']){
                /* 同城 */
                $freight = 0;
            }else{
                $freight = $goods_info['freight'];
            }
        }
        return $freight;
    }

    /**
     * 生成订单号
     * @param $user_id
     * @return string
     */
    public static function _createOsn($user_id, $channel, $pay_type){
        $orderSn = date('y')                            //获取年份对应的映射值
            . date('m')                                 //月份
            . date('d')                                //日期
            . $channel                       //当前时间戳 截取后5位
            . $pay_type                      //当前微秒数 截取
            . substr($user_id, -4)
            . self::_getMicrotime();
        return $orderSn;
    }

    public static function _getMicrotime(){
        $_time = number_format(microtime(true), 4, '', '');
        $_time = substr($_time, -10);
        return $_time;
    }
}
